package cn.com.se.网络.netty.client;

import io.netty.bootstrap.Bootstrap;
import io.netty.buffer.Unpooled;
import io.netty.channel.ChannelFuture;
import io.netty.channel.ChannelInitializer;
import io.netty.channel.ChannelOption;
import io.netty.channel.EventLoopGroup;
import io.netty.channel.nio.NioEventLoopGroup;
import io.netty.channel.socket.SocketChannel;
import io.netty.channel.socket.nio.NioSocketChannel;

import java.io.UnsupportedEncodingException;

/**
 * @Description TODO
 * @Author:hu.rl
 * @Date:2019-05-05 14:11
 * @Version 1.0
 **/
public class NettyClient {

    // 请求端主题
    public static void action(String ip, int port, String reqStr) throws InterruptedException, UnsupportedEncodingException {
        EventLoopGroup bossGroup = new NioEventLoopGroup();
        Bootstrap bs = new Bootstrap();
        bs.group(bossGroup)
                .channel(NioSocketChannel.class)
                .option(ChannelOption.SO_KEEPALIVE, true)
                .handler(new ChannelInitializer<SocketChannel>() {
                    @Override
                    protected void initChannel(SocketChannel socketChannel) throws Exception {
                        // 处理来自服务端的响应信息
                        socketChannel.pipeline().addLast(new ChannelClientHandler());
                    }
                });
        // 客户端开启
        ChannelFuture cf = bs.connect(ip, port).sync();
        // 发送客户端的请求
        cf.channel().writeAndFlush(Unpooled.copiedBuffer(reqStr.getBytes("UTF-8")));
        // 等待直到连接中断
        cf.channel().closeFuture().sync();
    }
}
